<template>
  <div class="table-wrap" v-loading="isShow">
    <div class="attachment-form">
      <el-form
        :model="parameter"
        ref="formRules"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div class="attachment-form-title">项目信息</div>
        </div>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="项目名称">
              <el-input
                v-model="parameter.projectName"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目地址">
              <el-input
                placeholder="请输入"
                v-model="parameter.projectAddress"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="勘测定界单位">
              <el-input
                placeholder="请输入"
                v-model="parameter.kcdjUnit"
                :disabled="!isDefaultTab || type !== 'edit'"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="验收单位">
              <el-input
                placeholder="请输入"
                v-model="parameter.ysUnit"
                :disabled="!isDefaultTab || type !== 'edit'"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="验收时间">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="parameter.ysTime"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
                :clearable="false"
                :disabled="!isDefaultTab || type !== 'edit'"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select
                placeholder="选择状态"
                v-model="parameter.status"
                clearable
                style="width: 100%"
                :disabled="!isDefaultTab || type !== 'edit'"
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div class="attachment-form-title">空间范围</div>
        </div>
        <el-row :gutter="24">
          <el-col :span="6" style="position: relative">
            <el-form-item label="界址点成果表（提供shp）">
              <!-- <el-input
                v-model="parameter.jzdcgb"
              ></el-input> -->
              <!-- <div style="border:1px solid #DCDFE6;height:100%;width: 100%;"> -->
              <el-input
                clear=""
                style="position: absolute"
                readonly=""
              ></el-input>
              <el-upload
                class="my_upload_jzdcgb"
                :http-request="beforeUploadJzdcgb"
                :on-preview="onPreview"
                :file-list="jzdcgbList"
                :before-upload="beforeUploadSize"
                style="height: 41px"
                action="#"
                :on-remove="onRemoveJzdcgb"
                :disabled="!isDefaultTab || type !== 'edit'"
                accept=".shp,.zip"
              >
                <!-- <el-button type="primary">上传</el-button> -->
                <span
                  @click="beforeUploadJzdcgb"
                  v-if="isDefaultTab && type !== 'detail'"
                >
                  <span class="upload-icon"></span>
                  <span class="upload-text">点击上传</span>
                </span>
              </el-upload>
              <!-- </div> -->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="test" class="test">
              <el-button
                size="small"
                class="preview-button"
                @click="previewMap()"
                >地图预览</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div class="attachment-form-title">附件材料</div>
        </div>
        <table class="table">
          <thead>
            <tr>
              <th>序号</th>
              <th>材料名称</th>
              <th style="width: 40%">上传文件</th>
              <th
                style="width: 20%"
                v-if="isDefaultTab && type !== 'detail'"
              >
                操作
              </th>
            </tr>
          </thead>
          <tbody
            v-for="(item, index) in parameter.fjClPoList"
            :key="index"
          >
            <tr>
              <td>{{ item.rank }}</td>
              <td>{{ item.name }}</td>
              <td style="" class="table_upload">
                <el-upload
                  class="upload"
                  :http-request="beforeUpload"
                  :on-preview="onPreview"
                  :file-list="item.landDataClFilePoList"
                  :before-upload="beforeUploadSize"
                  action="#"
                  style="position: relative"
                  :on-remove="onRemove"
                  :disabled="
                    !isDefaultTab || type !== 'edit'
                  "
                  accept=".doc,.docx,.pdf,.png,.jpg,.jpeg,.dwg,.mp4,.gif"
                  multiple
                >
                  <el-button
                    type="text"
                    @click="shangchuan(item)"
                    class="fileUpload"
                    v-if="isDefaultTab && type !== 'detail'"
                  >
                    <span
                      class="upload-icon"
                      v-if="true"
                    ></span>
                    <svg-icon
                      icon-class="uploadDeactive"
                      class="upload-deactive-icon"
                      font-size="20"
                      v-else
                    ></svg-icon>
                    <span
                      class="upload-text"
                      :class="
                        isDefaultTab
                          ? ''
                          : 'upload-text-disabled disabled'
                      "
                      >点击上传</span
                    >
                  </el-button>
                </el-upload>
              </td>
              <td v-if="isDefaultTab && type !== 'detail'">
                <div class="table-btn">
                  <!-- <div class="table-btn-item">上传</div> -->
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </el-form>
    </div>
    <customizeDialog
      :visible="dialogMapVisible"
      @update:visible="dialogMapVisible = $event"
      ref="dialog"
      :title="`${headerTitle}`"
      :titleTip="`当前面积：${currentArea}m²`"
      :width="'1200px'"
      top="100px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :has-footer="false"
      customPadding="0px"
    >
      <div
        v-loading="loading"
        element-loading-text="文件正在解析中，请稍后..."
      >
        <MapView
          :viewer-id="viewerId"
          :key="countMapLoad"
          @onload="onMapLoad"
        />
        <Utool
          :viewerId="viewerId"
          :position="{ top: '60px', right: '20px' }"
          :t="[]"
          :b="[
            {
              title: '初始位置',
              icon: 'dingwei'
            }
          ]"
          :showMore="false"
        ></Utool>
      </div> </customizeDialog
    >>
  </div>
</template>

<script>
import MapView from '@/components/mapView'
import { queryOptions } from '@/api/dict'
import {
  getKanJieDetail,
  shpResolveById,
  shpResolveGeojson
} from '@/api/kanjie'
import { downloadOneFile } from '@/api/projectRecord'
import { noticeFileUpload } from '@/api/wisdomBuild'
import {
  dwgFileUpload,
  queryJsgsList,
  dwgFileById,
  shpFileUpload,
  shpFileById
} from '@/api/projectMessage'
import Utool from '@/components/utool/index-land'
import * as turf from '@turf/turf'
import customizeDialog from '@/components/checkHistory/customizeDialog.vue'
let _layerManager, _viewer
const mapViewer = {}

export default {
  components: {
    MapView,
    Utool,
    customizeDialog
  },
  props: {
    currentTab: {
      type: [String, Number],
      default: '0'
    },
    pkid: String,
    type: { type: String, default: 'edit' },
    defaultIndex: {
      type: [Number, String],
      default: '0'
    }
  },
  computed: {
    isDefaultTab() {
      if (this.defaultIndex == this.currentTab) {
        console.log('是对的')
        return true
      } else {
        return false
      }
    }
  },
  data() {
    return {
      formRules: {},
      isShow: false,
      jzdcgbList: [],
      parameter: {
        area: ''
      },
      statusOptions: [],
      selectPkId: '',
      fileMode: null,
      dialogMapVisible: false,
      headerTitle: '',
      loading: false,
      viewerId: 'dwgMap',
      countMapLoad: 0,
      currentFeature: '',
      currentArea: 0
    }
  },
  async created() {
    await this.getStatusOptions()
    console.log(this.pkid)
    if (this.pkid !== '') {
      await this.getDetailData()
    }
  },
  mounted() {
    console.log(this.pkid)
  },
  methods: {
    onMapLoad({ id, viewer }) {
      console.log('渲染', viewer)
      _viewer = viewer
      _viewer.scene.imageryLayers.addImageryProvider(
        new Cesium.TiandituImageryProvider({
          mapStyle: null,
          token: 'a49a9220798216424e34b531cb3fa5b2',
          url: 'https://t0.tianditu.gov.cn/img_w/wmts'
        }),
        0
      )
      const geojson = _viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load(this.currentFeature)
      )
      _viewer.flyTo(geojson)
    },
    previewMap(type) {
      const info = this.parameter
      // const index = this.fileList.findIndex(
      //   (item) => item.type === type
      // )
      if (info.pkid) {
        if (info.jzdcgb && info.jzdcgb.fileId) {
          this.previewMapById(
            info.jzdcgb.fileId,
            info.jzdcgbJson
          )
          this.dialogMapVisible = true
        } else {
          this.$message.warning('请先上传文件再预览')
        }
      } else {
        if (index !== -1) {
          this.dialogMapVisible = true
          this.headerTitle = '地图预览'
          this.loading = true

          const params = new FormData()
          params.append('file', this.fileList[index].file)
          dwgFileUpload(params)
            .then((res) => {
              if (res.success) {
                this.currentFeature = JSON.parse(res.data)
                const area = turf.area(this.currentFeature)
                this.currentArea = area
                  ? area.toFixed(2)
                  : 0
                // this.dialogMapVisible = true
                this.countMapLoad++
              }
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          this.$message.warning('请先上传文件再预览')
        }
      }
    },

    // 通过文件id预览
    previewMapById(id, geojsonStr) {
      this.headerTitle = '地图预览'
      this.loading = true

      if (!geojsonStr) {
        shpResolveById(id)
          .then((res) => {
            console.log(res)
            if (res.success) {
              this.currentFeature = JSON.parse(res.data)
              const area = turf.area(this.currentFeature)
              this.currentArea = area ? area.toFixed(2) : 0
              // this.dialogMapVisible = true
              // 更新地图预览
              this.countMapLoad++
            }
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.currentFeature = JSON.parse(geojsonStr)
        const area = turf.area(this.currentFeature)
        this.currentArea = area ? area.toFixed(2) : 0
        // this.dialogMapVisible = true
        // 更新地图预览
        this.countMapLoad++
        this.loading = false
      }
    },
    getStatusOptions() {
      queryOptions('tdbz_status').then((res) => {
        if (res.success) {
          this.statusOptions = res.data.map((item) => {
            return {
              label: item.dictText,
              value: item.dictValue
            }
          })
        }
      })
    },
    getDetailData() {
      this.isShow = true
      console.log(this.pkid)
      getKanJieDetail(this.pkid).then((res) => {
        console.log(res)
        this.parameter = JSON.parse(
          JSON.stringify(res.data)
        )
        // 添加附件名
        this.jzdcgbList = [this.parameter.jzdcgb]

        this.addName(this.parameter)
        this.isShow = false
      })
    },
    addName(obj) {
      if (obj.fjClPoList) {
        for (let i = 0; i < obj.fjClPoList.length; i++) {
          for (const key2 in obj.fjClPoList[i]
            .landDataClFilePoList) {
            obj.fjClPoList[i].landDataClFilePoList[
              key2
            ].name =
              obj.fjClPoList[i].landDataClFilePoList[
                key2
              ].fileName
          }
        }
      }
      if (obj.jzdcgb) {
        obj.jzdcgb.name = obj.jzdcgb.fileName
      }
    },
    shangchuan(item) {
      console.log(item)
      this.selectPkId = item.pkid
    },
    onRemove(file, fileList) {
      const arr = this.parameter.fjClPoList.find(
        (item) => item.pkid == file.clId
      ).landDataClFilePoList
      console.log(arr, this.parameter)
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].fileId == file.fileId) {
          console.log('删这个', arr[i])
          arr.splice(i, 1)
        }
      }
      console.log(arr)
    },
    downloadDaochu(data, fileName) {
      const blob = new Blob([data]) // 把得到的结果用流对象转一下
      const a = document.createElement('a') // 创建一个<a></a>标签
      a.href = URL.createObjectURL(blob) // 将流文件写入a标签的href属性值
      a.download = fileName // 设置文件名
      a.style.display = 'none' // 障眼法藏起来a标签
      document.body.appendChild(a) // 将a标签追加到文档对象中
      a.click() // 模拟点击了a标签，会触发a标签的href的读取，浏览器就会自动下载了
      a.remove() // 一次性的，用完就删除a标签
    },
    xiazai(file) {
      downloadOneFile(file).then((res) => {
        this.downloadDaochu(
          res,
          file.fileName ? file.fileName : file.name
        )
      })
    },
    onPreview(file) {
      console.log(file)
      this.xiazai(file)
    },
    beforeUpload(file) {
      file = file.file
      const param = new FormData()
      param.append('file', file)
      noticeFileUpload(param).then(async (res) => {
        await this.parameter.fjClPoList
          .find((item) => item.pkid == this.selectPkId)
          .landDataClFilePoList.push({
            name: file.name,
            fileId: res.data
          })
      })
      console.log(this.parameter)
    },
    beforeUploadSize(file) {
      // if (file.size / (1024 * 1024) > 10) {
      //   // 限制文件大小
      //   alert('当前限制文件大小不能大于10M')
      //   return false
      // }
    },
    onRemoveJzdcgb(file, fileList) {
      this.jzdcgbList = []
      this.parameter.jzdcgb = {}
      this.parameter.jzdcgbJson = {}
      console.log(this.parameter)
    },
    beforeUploadJzdcgb(file) {
      const curretntFile = file.file
      this.fileMode = curretntFile
      const param = new FormData()
      param.append('file', curretntFile)
      shpResolveGeojson(param).then((res) => {
        if (res.success) {
          this.parameter.jzdcgb = {
            name: curretntFile.name,
            fileId: res.data.fileId
          }
          this.parameter.jzdcgbJson = res.data.geoJson
          this.jzdcgbList = [
            {
              name: curretntFile.name,
              fileId: res.data.fileId
            }
          ]
        }
      })
    },
    onExceed(file, fileList) {
      this.parameter.jzdcgb = {}
      this.jzdcgbList = []
      console.log(file)
      console.log(this.jzdcgbList)
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .my_upload_jzdcgb {
  .el-upload-list__item {
    width: 320px !important;
    position: relative;
    // .el-icon-upload-success{
    //   // position: absolute;
    //   // bottom: 0;
    //   // left: 0;
    //   display: none;
    // }
    // .el-icon-close{
    //   position: absolute;
    //   top: 0;
    //   right: 0;
    //   transform: translateY(20px);
    // }
  }
  .el-upload-list__item-name {
    width: 318px;
    height: 30px;
    /* top: 0; */
    position: absolute;
    top: 0;
    left: 0;
  }
  .el-upload {
    position: absolute !important;
    // right: -25% !important;
    // top: 50% !important;
    top: -120%;
    right: 25%;
    // transform: translate(50%, -50%) !important;
    &-list {
      &__item {
        margin-top: 0px;
        .el-upload-list__item-name {
          :first-child {
            margin-top: 8px;
          }
          :last-child {
            margin-bottom: 8px;
          }
        }
        .el-upload-list__item-status-label {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
        }
        .el-icon-close {
          position: absolute;
          top: 50% !important;
          transform: translateY(90%) !important;
          // right: 0;
        }
        .el-icon-upload-success {
          position: absolute;
          top: 50% !important;
          transform: translateY(90%) !important;
          right: 0;
        }
      }
    }
  }
}
::v-deep .table_upload {
  .el-upload {
    position: absolute !important;
    right: -25% !important;
    top: 50% !important;
    transform: translate(50%, -50%) !important;
    &-list {
      &__item {
        margin-top: 0px;
        .el-upload-list__item-name {
          :first-child {
            margin-top: 8px;
          }
          :last-child {
            margin-bottom: 8px;
          }
        }
        .el-upload-list__item-status-label {
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
        }
        .el-icon-close {
          // position: absolute;
          top: 50% !important;
          transform: translateY(-50%) !important;
        }
      }
    }
  }
}
.upload {
  //   .el-upload-list--text{
  //   position: absolute !important;
  //   right: -25% !important;
  //   top: 50% !important;
  //   transform: translate(50%,-50%) !important;
  // }
  cursor: pointer;
  // height: 0px;

  &-text {
    // position: absolute;
    // top: -35px;
    // left: 260px;
    color: #00baff;
    // display: none;
  }
  &-text-disabled {
    color: rgb(176, 176, 176);
  }
  &-icon {
    // position: absolute;
    position: absolute !important;
    right: -25% !important;
    top: 50% !important;
    transform: translate(50%, -50%) !important;
    width: 16px;
    height: 14px;
    // top: -22px;
    // left: 240px;
    background: url('~@/assets/images/wisdom-construction/upload-file.png');
    background-size: 100% 100%;
  }
  &-deactive-icon {
    position: absolute !important;
    right: -25% !important;
    top: 50% !important;
    transform: translate(50%, -50%) !important;
    width: 16px;
    height: 14px;
  }
  .fileUpload {
    position: absolute !important;
    right: -25% !important;
    top: 50% !important;
    transform: translate(50%, -50%) !important;
  }

  .el-upload-list__item {
    margin-top: 0px !important;
  }
}
.attachment-form {
  padding: 0 27px;
  &-title {
    color: #4c565c;
    display: flex;
    align-items: center;
    margin: 18px 0 14px 0;
    font-size: 16px;
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 14px;
      background: linear-gradient(180deg, #40ebff, #bcf8ff);
      margin-right: 7px;
    }
  }
  .table {
    border-collapse: collapse;
    width: 100%;
    box-sizing: border-box;
    margin-left: 7px;
    margin-bottom: 80px;
    thead {
      background-color: #f2f6fb;
    }
    td,
    th {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #6b767d;
      line-height: 42px;
      border: 1px solid #f2f6fb;
      text-align: center;
    }
    td {
      font-weight: normal;
    }
    tbody {
      tr {
        td {
          &:nth-child(1) {
            width: 50px;
          }
          &:nth-child(2) {
            width: 300px;
          }
          &:nth-child(3) {
            width: 300px;
          }
          &:nth-child(4) {
            max-width: 1000px;
          }
          &:nth-child(5) {
            width: 300px;
          }
        }
      }
    }
  }
}
.disabled {
  cursor: default;
}
.myupload {
  cursor: pointer;
  height: 0px;

  &-text {
    position: absolute;
    top: -35px;
    left: 260px;
    color: #00baff;
  }

  &-icon {
    position: absolute;
    width: 16px;
    height: 14px;
    top: -22px;
    left: 240px;
    background: url('~@/assets/images/wisdom-construction/upload-file.png');
    background-size: 100% 100%;
  }
}
::v-deep {
  .el-input__inner {
    width: 320px !important;
    height: 32px !important;
    overflow: hidden !important;
  }
  .el-dialog {
    .cesium-viewer {
      height: 520px !important;
    }
  }
}
.preview-button {
  background: #497fa3;
  border: 1px solid #497fa3;
  border-radius: 2px;
  color: white;
}
::v-deep .test {
  .el-form-item__label {
    opacity: 0;
  }
}
</style>
